from django.contrib.auth.forms import UserCreationForm
from django.utils.translation import gettext_lazy as _
from django import forms
from django.contrib.auth.models import Group

from crispy_forms.helper import FormHelper

from .models import CustomUser


class MyUserCreationForm(UserCreationForm):

    terms_of_use = forms.BooleanField(
        label=_('I agree to terms of use of this website.'))

    class Meta:
        model = CustomUser
        fields = ('username', 'email', 'password1',
                  'password2', 'terms_of_use')

    def save(self, commit=True):
        user = super().save(commit=False)

        user.is_active = False
        user.is_staff = True

        if commit:
            user.save()

        # append the default group permissions to this user.
        groups = Group.objects.filter(name='default_account_perms')
        user.groups.set(groups)

        return user
